package cn.javase.base.io._01_File相关的流;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamTest {

    /* 写出数据 */
    @Test
    public void testFileOutputStream() {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("D:\\Code\\study\\JavaCode\\JavaSEDemo\\base\\src\\main\\java\\cn\\javase\\base\\io\\_01_File相关的流\\2.txt");
            String str = "aBcDeFgH";
            fos.write(str.getBytes());
            fos.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /* 文件复制 */
    @Test
    public void testFileOutputStream2() throws FileNotFoundException {
        String uri = "D:\\Code\\study\\JavaCode\\JavaSEDemo\\base\\src\\main\\java\\cn\\javase\\base\\io\\_01_File相关的流\\video.mp4"; // 定义资源路径
        FileInputStream fis = new FileInputStream(uri);
        FileOutputStream fos = new FileOutputStream(uri.replace("video", "video_copy"));
        byte[] bytes = new byte[1024]; // 每次读取1KB
        int len;
        try {
            while ((len = fis.read(bytes)) != -1) {;
                fos.write(bytes, 0, len);
            }
            fos.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fis.close();
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
